#include "stdafx.h"


ParticleSystem::ParticleSystem(void)
{
}


ParticleSystem::~ParticleSystem(void)
{
}


void ParticleSystem::addEmitter(ParticleEmitter& emitter)
{
	mEmitters.push_back(&emitter);
}


void ParticleSystem::update(float elapsedTime)
{
	globals::d3dDevice->SetRenderState( D3DRS_POINTSPRITEENABLE, TRUE );
	globals::d3dDevice->SetRenderState( D3DRS_POINTSCALEENABLE,  TRUE );
	globals::d3dDevice->SetRenderState( D3DRS_POINTSIZE_MIN, FtoDW(1.0f) );
	globals::d3dDevice->SetRenderState( D3DRS_POINTSCALE_A,  FtoDW(0.0f) );
	globals::d3dDevice->SetRenderState( D3DRS_POINTSCALE_B,  FtoDW(0.0f) );
	globals::d3dDevice->SetRenderState( D3DRS_POINTSCALE_C,  FtoDW(1.0f) );
	globals::d3dDevice->SetRenderState( D3DRS_ZWRITEENABLE, FALSE );
	globals::d3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, TRUE );
	globals::d3dDevice->SetRenderState(D3DRS_SRCBLEND, D3DBLEND_SRCALPHA);
	globals::d3dDevice->SetRenderState(D3DRS_DESTBLEND, D3DBLEND_INVSRCALPHA);
	globals::d3dDevice->SetRenderState(D3DRS_BLENDOP, D3DBLENDOP_ADD);

	for(auto e : mEmitters)
	{
		e->Update(elapsedTime);
		e->render();
	}

    globals::d3dDevice->SetRenderState( D3DRS_POINTSPRITEENABLE, FALSE );
    globals::d3dDevice->SetRenderState( D3DRS_POINTSCALEENABLE,  FALSE );
	globals::d3dDevice->SetRenderState( D3DRS_ZWRITEENABLE, TRUE );
	globals::d3dDevice->SetRenderState( D3DRS_ALPHABLENDENABLE, FALSE );
}


void ParticleSystem::toLua()
{
	using luabind::def;
	using luabind::class_;

	luabind::module(lua::State())
	[
		class_<ParticleSystem>("ParticleSystem").
		def(luabind::constructor<>()).
		def("addEmitter", &ParticleSystem::addEmitter).
		def("update", &ParticleSystem::update)
	];
}